var entity = require('../entity');
var Relation = entity.Relation;
var User = require('../proxy').User;
var Faction = require('../proxy').Faction;
var FactionMember = require('../proxy').FactionMember;
var redisManager = require('../proxy').RedisManager;
var logger = require('../service/Logger');

exports.initUserCache = function(){
    User.getAllUsers(function(err, users){
        if(err){
            logger.error(err.message);
            return;
        }
        for(var i in users){
            var user = users[i];
            redisManager.putUserIntoCache(user, function(err, resp){
                if(err){
                    logger.error(err.message);
                    return;
                }
            })
        }
    })
}

exports.initUserFriends = function(){
    User.getAllUsers(function(err, users){
        for(var i in users){
            (function(user){
                Relation.find({userone: user._id}).exec(function(err, rels){
                    for(var j in rels){
                        (function(rel){
                            redisManager.addUserFriend(user._id, rel.weight, {id:rel.usertwo}, function(err, resp){
                                console.log('['+user.name+'] add friend :'+rel.usertwo);
                            })
                        })(rels[j])
                    }
                })
            })(users[i])
        }
    })
}

exports.initUserSet = function(){
    User.getAllUsers(function(err, users){
        for(var i in users){
            (function(user){
                Relation.find({userone: user._id}).exec(function(err, rels){
                    console.log(rels.length)
                    for(var j in rels){
                        (function(rel){
                            redisManager.addUserSet(user._id, {id:rel.usertwo}, function(err, resp){
                                console.log('['+user.name+'] add set :'+rel.usertwo);
                            })
                        })(rels[j])
                    }
                })
            })(users[i])
        }
    })
}

exports.initFactionMembers = function(){
    Faction.getAllFactions(function(err, factions){
        console.log(factions.length)
        for(var i in factions){
            (function(faction){
                FactionMember.getAllMembers(faction._id, function(err, fms){
                    for(var j in fms){
                        (function(fm){
                            redisManager.addFactionMember(faction._id, fm.member.id, function(err, data){
                                console.log('['+fm.member.name+'] add faction :'+faction.name);
                            })
                        })(fms[j])
                    }
                })
            })(factions[i])
        }
    });
}